<template>
   <Spin :spinning="state.loading">
    <Transfer
      v-model:target-keys="stateValue.targetKeys"
      :data-source="stateValue.dataSource"
      show-search
      :list-style="{
        width: '90%',
        minWidth: '300px',
        height: 'calc(100vh - 300px)',
      }"
      :render="(item) => `${item.title} ${item.apiAction}`"
      :pagination="state.pagination"
      @search="handleSearch"
      @change="handleChange"
    >
      <template #footer="{ direction }">
        <div :class="`${prefixCls}-action-type`">
          <JDictSelectTag 
            v-if="direction === 'left'" 
            :placeholder="'操作类型'" :dictCode="state.actionTypeDict" 
            @change="handleActionTypeChange"
           />
        </div>
      </template>
      <template #notFoundContent>
        <Empty class="!mt-4" />
      </template>
    </Transfer>
  </Spin>
</template>
<script lang="ts" setup>
  import { Empty, Spin, Transfer } from "ant-design-vue"
  import { ref, computed, unref, onUnmounted, onMounted, toRaw, watch, nextTick } from "vue"
  import { listApiResource, type RamResource } from "/@/api/iam/resource"
  import { useDesign } from "/@/hooks/web/useDesign"
  import { PopConfirmButton } from "/@/components/Button"
  import { isArray, isFunction } from "/@/utils/is"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { JDictSelectTag } from "/@/components/Form"
  const { createMessage } = useMessage()

  const emit = defineEmits(["update:actions", "change"])
  const { prefixCls } = useDesign("api-perm")

  interface DataSource {
    key: string
    title: string
    actionType: string
    actions: string[]
    chosen: boolean
  }

  interface State {
    // 树的全部节点信息
    allTreeKeys: any[]
    //树的选择节点信息
    checkedKeys: any[]
    halfCheckedKeys: any[]
    defaultCheckedKeys: any[]

    resourceList: RamResource[]
    targetKeys: string[]
    dataSource: DataSource[]
    actionTypeDict: string
    actionType?: string
    loading?: boolean
    timer?: any
    pagination: any
    record: any
  }

  const state = ref<State>({
    allTreeKeys: [],
    checkedKeys: [],
    halfCheckedKeys: [],
    defaultCheckedKeys: [],

    resourceList: [],
    targetKeys: [],
    dataSource: [],
    loading: false,
    pagination: {
      pageSize: 20,
    },
    actionTypeDict: "ram_resource_action_type",
    record: {},
  })
  const stateValue = state.value

  const props = defineProps({
    actions: { type: Array as PropType<string[]>, required: false },
    iamCode: { type: String, required: false },
    apiNamespaceCode: { type: String, required: false },
  })

  const loadResource = async () => {
    console.log('=====> props', JSON.stringify(props))

    const actions = toRaw(props?.actions && props?.actions?.length > 0 ? props.actions : [])
    const iamCode = props.iamCode || (actions.length > 0 ? actions[0].split(':')[0] : null)
    if (!iamCode || iamCode == '*') {
      return
    }
    stateValue.loading = true
    try {
      stateValue.resourceList = (await listApiResource({ iamCode, apiNamespaceCode: props.apiNamespaceCode })) as RamResource[]
      stateValue.dataSource = stateValue.resourceList.map((e) => ({
        key: e.apiAction,
        title: e.apiSummary,
        actionType: e.actionType,
        url: e.url,
        apiAction: e.apiAction,
        chosen: Math.random() * 2 > 1,
      }))

      stateValue.targetKeys = stateValue.dataSource.map(e => actions.findIndex(e1 => e1 == e.key) >= 0 ? e.key : null).filter( e => e != null)
    } finally {
      stateValue.loading = false
    }
  }

  onMounted(async () => {
    loadResource()
  })

  watch(
    () => props.iamCode,
    (iamCode : any) => {
      iamCode &&
        nextTick(() => {
          loadResource()
        })
    }
  )

  const handleChange = (keys: string[], direction: string, moveKeys: string[]) => {
    console.log('keys', keys)
    if (direction === "right") {
      
    }
    stateValue.targetKeys = keys
    emit('update:actions', keys)
    emit('change', keys)
  }

  onUnmounted(() => {
    clearTimeout(stateValue.timer)
  })

  const handleActionTypeChange = async (value) => {
    if (isArray(value)) {
      return
    }
    stateValue.actionType = value
    console.log("actionType: ", value)
    try {
      stateValue.dataSource = stateValue.resourceList
        .filter((e) => !value || e.actionType === value)
        .map((e) => ({
          key: e.action + "_" + e.name,
          title: e.name,
          actionType: e.actionType,
          actions: e.action,
          chosen: Math.random() * 2 > 1,
        }))
    } finally {
    }
  }

  const handleSearch = () => {}

</script>

<style lang="less">
  @prefix-cls: ~"@{namespace}-api-perm";
  .@{prefix-cls} {
    &-action-type {
      margin: 5px;

      .ant-select-single {
        width: 110px !important;
      }
    }
  }

  .ant-transfer .ant-transfer-operation .ant-btn {
    .anticon {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>
